package vip.aster.framework.mybatis.config;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import jakarta.annotation.Resource;
import org.apache.ibatis.type.LocalDateTimeTypeHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import vip.aster.framework.mybatis.handler.OracleLocalDateTimeTypeHandler;
import vip.aster.framework.mybatis.handler.MybatisPlusMetaObjectHandler;
import vip.aster.framework.mybatis.interceptor.AsterDataPermissionInterceptor;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * mybatis-plus配置
 *
 * @author Aster
 * @since 2023/11/24 15:31
 */
@Configuration
public class MybatisPlusConfig {

    @Value("${data-permission.enable}")
    private boolean enableDataPermission;
    @Resource
    private DataSource dataSource;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        if (enableDataPermission) {
            // 数据权限插件
            interceptor.addInnerInterceptor(asterDataPermissionInterceptor());
        }
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        // 防全表更新与删除
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());

        return interceptor;
    }

    @Bean
    public MybatisPlusMetaObjectHandler mybatisPlusMetaObjectHandler() {
        return new MybatisPlusMetaObjectHandler();
    }

    @Bean
    public AsterDataPermissionInterceptor asterDataPermissionInterceptor() {
        return new AsterDataPermissionInterceptor();
    }

    @Bean
    public LocalDateTimeTypeHandler asterLocalDateTimeTypehandler() throws SQLException {
        Connection connection = dataSource.getConnection();
        String dbType = connection.getMetaData().getDatabaseProductName();
        if (StrUtil.equalsAny(dbType, "Oracle")) {
            return new OracleLocalDateTimeTypeHandler();
        }
        return new LocalDateTimeTypeHandler();
    }

}
